package com.ls.herostory.mq;

import com.alibaba.fastjson.JSON;
import com.ls.herostory.thread.MyThreadFactory;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.*;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/14 15:56
 * @since
 */
public class MqProducer {
    private final static Logger logger = LoggerFactory.getLogger(MqProducer.class);

    private static MqProducer mqProducer = new MqProducer();

    private Channel channel;

    private MqProducer(){
        try{
            init();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }
    }

    public static MqProducer getInstance(){
        return mqProducer;
    }

    private void init(){
        ConnectionFactory connectionFactory = MqConnectionFactoryUtil.getConnectionFactory();
        try {
            Connection connection = connectionFactory.newConnection();

            channel = connection.createChannel();

            // 定义交换机
            channel.exchangeDeclare("rank", "fanout", true, false, null);
            // 定义队列
            channel.queueDeclare("rank", true, false, false, null);
            // 队列绑定交换机
            channel.queueBind("rank", "rank", "#");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    public synchronized void productAttkMsg(AttkMsg msg) {
        String json = JSON.toJSONString(msg);
        AMQP.BasicProperties properties = MessageProperties.BASIC;
        try {
            channel.basicPublish("rank", "rank", properties, json.getBytes());
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

}
